輪播動畫 原生要處理的話印象中是PageView
先建立一個widget class, 將package的封裝一次
construct傳入將要顯示的資料與點擊事件回傳
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'dart:math';
class CarouselSlide extends StatelessWidget {
CarouselSlide({Key? key, required this.dataList, required this.didSelected})
: super(key: key);
final List dataList;
final Function(int index) didSelected;
@override
Widget build(BuildContext context) {
return CarouselSlider(
options: CarouselOptions(
height: MediaQuery.of(context).size.width * 0.86 * 9 / 16,
aspectRatio: 16 / 9,
enableInfiniteScroll: true,
autoPlay: true,
autoPlayInterval: const Duration(seconds: 2),
),
items: dataList.map((element) {
final index = dataList.indexOf(element);
return GestureDetector(
onTap: () => didSelected(index),
child: Container(
margin: EdgeInsets.symmetric(horizontal: 5.0),
decoration: BoxDecoration(color: Colors.transparent),
child: Stack(
alignment: Alignment.center,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Container(
color: Colors.primaries[
Random().nextInt(Colors.primaries.length)]),
),
Positioned(
child: Text(
"$index",
style: TextStyle(fontSize: 30, color: Colors.white),
),
),
],
),
),
);
}).toList(),
);
}
}
CarouselOptions內的屬性設定
autoPlay:
是否自動換下一張, autoPlayInterval:換下一張間格幾秒
enableInfiniteScroll:
是否無限輪播,scrollDirection: 滑動方向(預設水平方向)
實際使用的頁面, 呼叫剛封裝的class
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:it_home/component/CarouselSlide.dart';
import 'package:it_home/pages/carousel_slider/CarouselSlidePageController.dart';
class CarouselSlidePage extends GetView<CarouselSlidePageController> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('SliderListPage')),
body: SafeArea(
child: Center(
child: CarouselSlide(
dataList: controller.dataList,
didSelected: (int index) {
print("didTapped $index");
},
),
),
),
);
}
}
因為有用到GetxController這邊也把程式碼一併放在這邊
生成一個List用於資料顯示
import 'package:get/get.dart';
class CarouselSlidePageController extends GetxController {
final _dataList = [].obs;
get dataList => this._dataList;
@override
void onInit() {
_dataList.assignAll(Iterable<int>.generate(10).toList());
super.onInit();
}
}
最後畫面如下
下一篇將為大家介紹shared preferences